<?php
namespace Home\Controller;
use Overtrue\Pinyin\Pinyin;
use Think\Controller;

/**
 * Created by PhpStorm.
 * User: krasen
 * Date: 2015/5/23
 * Time: 19:13
 */
class CategoryController extends Controller
{
    public function add()
    {
        $categoryModel = D('Category');
        if(IS_POST){
            if($data = $categoryModel->create()){
                if($categoryModel->add()){
                    $this->success('添加成功');
                }else
                    $this->error($categoryModel->getDbError());
            }else{
                $this->error($categoryModel->getError());
            }
        }else{
            $topCat = $categoryModel->where(array('sc_pid' => 1))->select();
            $this->assign('topCat', $topCat);
            $this->assign('pid', I('GET.pid'));
            $this->assign('action', U('Category/add'));
            $this->display();
        }

    }

    public function lists()
    {
        $categoryModel = D('Category');
        $pid = I('GET.pid', 1, 'intval');
        $result = $categoryModel->where(array('sc_pid' => $pid))->select();
        $this->assign('cats', $result);
        $this->display();
    }

    public function modify()
    {
        $id = I('GET.id', 0, 'intval');
        $categoryModel = D('Category');
        if(!$id){
            $this->error('逗比你怎么点的');
        }
        if(IS_POST){
            if($categoryModel->create()){
                if($categoryModel->save()){
                    $this->success('修改成功');
                }else{
                    $this->error($categoryModel->getDbError());
                }
            }else{
                $this->error($categoryModel->getError());
            }
        }else{
            $topCat = $categoryModel->where(array('sc_pid' => 1))->select();
            $this->assign('topCat', $topCat);
            $result = $categoryModel->getByScId($id);
            $this->assign('pid', $result['sc_pid']);
            $this->assign('cat', $result);
            $this->display('add');
        }
    }

    public function remove()
    {
        $id = I('GET.id', 0, 'intval');
        if(!$id){
            $this->error('逗比你怎么点的');
        }
        if(IS_POST){

        }else{
            $this->display();
        }
    }

    public function pinyin()
    {
        if(IS_AJAX){
            $name = I('POST.name', '', 'strval');
            $this->success(Pinyin::trans($name));
        }
    }

    public function cache()
    {

    }
}